import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:sui_shou_pai/Utils/storage_util.dart';
import 'package:sui_shou_pai/module/effect.dart';
import 'package:sui_shou_pai/my/init_info/init_information.dart';
import 'package:sui_shou_pai/network/http_config.dart';
import 'package:sui_shou_pai/network/http_request.dart';
import 'package:sui_shou_pai/record/image_widget.dart';
import 'package:sui_shou_pai/record/record_card_list.dart';
import 'package:sui_shou_pai/record/record_detail.dart';
import 'package:sui_shou_pai/record/record_entity/photo_record_entity.dart';

class MyPhotoRecord extends StatefulWidget {
  const MyPhotoRecord({Key key}) : super(key: key);

  @override
  MyPhotoRecordState createState() => MyPhotoRecordState();
}

List<PhotoRecordEntity> photoRecordEntityList = [];
List<PhotoRecordEntity> plist = [];

class MyPhotoRecordState extends State<MyPhotoRecord> {
  List<dynamic> tempList = [];
  int pageNum;
  int pages;
  String loading;

  ScrollController _scrollController;
  bool isLoading = false;

  // 请求数据
  Future<void> getData() async {
    plist.clear();
    HttpRequest.request(
      "$BASE_URL/photo-record/getMyRecords",
      data: {
        "employeeId": InitInformation.employeeId,
        "pageNum": "1",
        "pageSize": "6"
      },
      token: await StorageUtil.getStringItem("token"),
      method: "post",
    ).then((value) {
      var data = jsonDecode(value.toString());
      List<dynamic> res = data['result']['records'];

      for (int i = 0; i < res.length; i++) {
        PhotoRecordEntity photoRecordEntity =
            PhotoRecordEntity.fromJson(res[i]);
        plist.add(photoRecordEntity);
      }
      setState(() {
        // getData();
        pages = data['result']['pages'];
        if (pageNum == pages) {
          loading = "你已滑到世界尽头";
        }
        photoRecordEntityList.clear();
        if (plist.isNotEmpty) {
          for (int i = 0; i < plist.length; i++) {
            photoRecordEntityList.add(plist[i]);
          }
        }
      });
    });
  }

  // 图片字符串拼接
  String imageSplit(String image) {
    List<String> imageList = image.split(',');
    if (imageList.isNotEmpty) {
      return imageList[0];
    } else
      return null;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();

    pageNum = 1;
    loading = "加载中";
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
              _scrollController.position.maxScrollExtent &&
          pageNum < pages) {
        _loadMore();
      }
    });
    // 新建监听
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("我的拍照记录"),
      ),
      body: RefreshIndicator(
        onRefresh: onRefresh,
        child: Center(
          child: Column(
            children: [
              Flexible(
                child: GridView.count(
                  // 方向，这行没设置页可以，默认就是垂直的
                  scrollDirection: Axis.vertical,
                  //水平子Widget之间间距
                  crossAxisSpacing: 10.0,
                  //垂直子Widget之间间距
                  mainAxisSpacing: 10.0,
                  //GridView内边距
                  padding: EdgeInsets.all(10.0),
                  //一行的Widget数量
                  crossAxisCount: 2,
                  //子Widget宽高比例
                  childAspectRatio: 0.75,
                  // 比如2.0，就是 宽/高=2
                  //子Widget列表
                  children: getWidgetList(context),
                  controller: _scrollController,
                ),
              ),
              _buildLoadMoreItem()
            ],
          ),
        ),
      ),
    );
  }

  // 下拉刷新
  Future<void> onRefresh() async {
    setState(() {
      getData();
    });
    Fluttertoast.showToast(
        msg: "刷新成功",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.black,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  List<String> getDataList() {
    List<String> list = [];
    for (int i = 0; i < photoRecordEntityList.length; i++) {
      list.add(i.toString());
    }
    return list;
  }

  List<Widget> getWidgetList(BuildContext context) {
    return getDataList()
        .map((item) => getItemContainer(item, context))
        .toList();
  }

  Widget getStatus(int index) {
    var statusColor;
    var title;
    if (photoRecordEntityList[index].status.isNotEmpty) {
      if (photoRecordEntityList[index].status == "1") {
        statusColor = Colors.green;
        title = "已通过";
      } else if (photoRecordEntityList[index].status == "2") {
        statusColor = Colors.yellow;
        title = "执行中";
      } else {
        statusColor = Colors.red;
        title = "已提交";
      }
    }
    return Container(
        alignment: Alignment.bottomCenter,
        width: 45,
        height: 20,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(7.0)),
            color: statusColor),
        child: Center(
            child: Text(
          title,
        )));
  }

  // 设置获取图片
  Widget getPicture(PhotoRecordEntity photoRecordEntity) {
    if (imageSplit(photoRecordEntity.image) == "" ||
        imageSplit(photoRecordEntity.image) == null ||
        imageSplit(photoRecordEntity.image) == "null") {
      return Image.asset(
        "assets/images/news_image_02.png",
        fit: BoxFit.cover,
      );
    } else {
      return Image.network(
        imageSplit(photoRecordEntity.image),
        fit: BoxFit.cover,
      );
    }
  }

  Widget getItemContainer(String item, BuildContext context) {
    var index = int.parse(item);
    return Container(
        // alignment: Alignment.center,
        // child: Text(
        //   item,
        //   style: TextStyle(color: Colors.white, fontSize: 20),
        // ),
        decoration: BoxDecoration(
          boxShadow: [shadowOffsetY2()],
        ),
        // color: Colors.blue,
        child: Column(
          children: <Widget>[
            Expanded(
              child: GestureDetector(
                child: Card(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(15.0)),
                    ),

                    // 抗锯齿
                    clipBehavior: Clip.antiAlias,
                    // elevation: 20,
                    // 阴影大小
                    child: new Container(
                        child: Stack(
                      children: <Widget>[
                        ConstrainedBox(
                          constraints: const BoxConstraints.expand(),
                          // 使用本地图片
                          // child: Image.asset("assets/images/news_image_02.png", fit: BoxFit.cover,),
                          // 使用网络图片
                          // child: (imageSplit(photoRecordEntityList[index].image)!=null)?Image.network(
                          //   imageSplit(photoRecordEntityList[index].image),
                          //   fit: BoxFit.cover,
                          // ):Image.asset(
                          //   "assets/images/news_image_02.png",
                          //   fit: BoxFit.cover,
                          // )
                          //child: getPicture(photoRecordEntityList[index]),
                          //child: tryGetPicture(photoRecordEntityList[index]),
                          child: ImageWidget(
                              url: imageSplit(
                                  photoRecordEntityList[index].image)),
                        ),
                        Container(
                            alignment: Alignment.topRight,
                            padding: EdgeInsets.only(top: 10, right: 10),
                            child: ClipRect(
                              child: BackdropFilter(
                                filter: ImageFilter.blur(
                                    sigmaX: 10.0, sigmaY: 10.0),
                                child: Opacity(
                                  opacity: 0.85,
                                  // 获取右上角标识栏
                                  child: getStatus(index),
                                ),
                              ),
                            )),
                        Container(
                            alignment: Alignment.bottomCenter,
                            child: ClipRect(
                              child: BackdropFilter(
                                filter: ImageFilter.blur(
                                    sigmaX: 10.0, sigmaY: 10.0),
                                child: Opacity(
                                  opacity: 0.5,
                                  child: Container(
                                    alignment: Alignment.bottomCenter,
                                    width: 200,
                                    height: 70,
                                    decoration:
                                        BoxDecoration(color: Colors.white),
                                    child: Center(
                                      child: Column(
                                        children: <Widget>[
                                          // 内容
                                          Container(
                                            padding:
                                                EdgeInsets.only(left: 10.0),
                                            child: Row(
                                              children: <Widget>[
                                                Expanded(
                                                    child: Text(
                                                  photoRecordEntityList[index]
                                                      .content,
                                                  maxLines: 1,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style: TextStyle(
                                                      fontSize: 15.0,
                                                      color: Colors.black,
                                                      letterSpacing: 1.0),
                                                ))
                                              ],
                                            ),
                                          ),
                                          // 部门
                                          Container(
                                            padding: EdgeInsets.only(
                                                left: 10.0, top: 5.0),
                                            child: Row(
                                              children: <Widget>[
                                                Icon(Icons.ad_units_rounded,
                                                    color: Colors.black,
                                                    size: 10.0),
                                                SizedBox(
                                                  width: 5.0,
                                                ),
                                                Text(
                                                  photoRecordEntityList[index]
                                                      .location,
                                                  maxLines: 1,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style: TextStyle(
                                                      fontSize: 10,
                                                      color: Colors.black,
                                                      letterSpacing: 1.0),
                                                )
                                              ],
                                            ),
                                          ),
                                          // 时间和员工姓名
                                          Container(
                                            padding: EdgeInsets.only(
                                                left: 10.0, top: 5.0),
                                            child: Row(
                                              children: <Widget>[
                                                Icon(Icons.access_time_sharp,
                                                    color: Colors.black,
                                                    size: 10.0),
                                                SizedBox(
                                                  width: 5.0,
                                                ),
                                                Container(
                                                  child: Text(
                                                    photoRecordEntityList[index]
                                                        .updateTime,
                                                    maxLines: 1,
                                                    style: TextStyle(
                                                        fontSize: 10,
                                                        color: Colors.black,
                                                        letterSpacing: 1.0),
                                                  ),
                                                ),
                                                SizedBox(
                                                  width: 20.0,
                                                ),
                                                Icon(
                                                    Icons
                                                        .perm_identity_outlined,
                                                    color: Colors.black,
                                                    size: 10.0),
                                                SizedBox(
                                                  width: 5.0,
                                                ),
                                                Text(
                                                  photoRecordEntityList[index]
                                                      .publisherName,
                                                  maxLines: 1,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style: TextStyle(
                                                      fontSize: 10,
                                                      color: Colors.black,
                                                      letterSpacing: 1.0),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                        //style: Theme.of(context).textTheme.display3,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ))
                      ],
                    )
                        // width: 200,
                        // height: 100,
                        // alignment: Alignment.topCenter,
                        // child: Image.asset(
                        //   'assets/images/1.jpeg',
                        //   fit: BoxFit.fill,
                        //   width: 200,
                        //   height: 140,
                        // )
                        //child: new Text("Card Widget",style: TextStyle(color: Colors.white),),
                        )),
                onTap: () {
                  Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => RecordDetail(),
                              settings: RouteSettings(
                                  arguments: photoRecordEntityList[index])))
                      .then((value) {
                    getData();
                    build(context);
                  });
                },
              ),
            )
          ],
        ));
  }

  Future<Null> _loadMore() async {
    if (!isLoading) {
      setState(() {
        isLoading = true;
      });

      await Future.delayed(Duration(seconds: 2), () {
        setState(() {
          isLoading = false;
          if (pageNum < pages) {
            pageNum = pageNum + 1;
            if (pageNum == pages) {
              loading = "你已滑到世界尽头";
            }
            HttpRequest.request("$BASE_URL/photo-record/getMyRecords",
                method: "post",
                data: {
                  "employeeId": InitInformation.employeeId,
                  "pageNum": pageNum.toString(),
                  "pageSize": "5"
                }).then((value) {
              List<dynamic> loadMoreData = [];
              setState(() {
                loadMoreData =
                    json.decode(value.toString())['result']['records'];
                for (int i = 0; i < loadMoreData.length; i++) {
                  plist.add(PhotoRecordEntity.fromJson(loadMoreData[i]));
                }
              });
            });
          } else {}
        });
      });
    }
  }

  Widget _buildLoadMoreItem() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Text(loading),
      ),
    );
  }
}
